package com.express.core.controller;

import com.express.common.SysParamterUtil;
import com.express.conf.WechatConfig;
import com.express.entity.Address;
import com.express.entity.User;
import com.express.entity.UserOrders;
import com.express.mybatis.PageResult;
import com.express.mybatis.Result;
import com.express.service.IAddressService;
import com.express.service.IOrderService;
import com.express.service.IWxUserService;
import com.express.sys.service.UserService;
import com.express.util.wx.WeixinUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查快递控制类
 */
//@Api(tags = "查快递模块")
@Controller
public class CheckExpController {

    private static final Logger logger = LoggerFactory.getLogger(CheckExpController.class);

    @Autowired
    IOrderService orderService;
    @Autowired
    IAddressService addressService;
    @Autowired
    UserService userService;
    @Autowired
    SysParamterUtil paramterUtil;

    @Autowired
    IWxUserService wxUserService;

    @RequestMapping("toCheckExp")
    public ModelAndView toCheckExp(Object obj,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("examine");
        modelAndView.addObject("cancelTime",paramterUtil.getParametValue("order_cancel"));
        modelAndView.addObject("editTime",paramterUtil.getParametValue("order_edit"));
        modelAndView.addObject("sysUserId",request.getSession().getAttribute("sysUserId"));
        return modelAndView;
    }

    @RequestMapping("addLogin")
    @ResponseBody
    public Result addLogin(String username,String password,HttpServletRequest request) {
        User user = userService.addLogin(username, password);
        Result result = new Result();
        if(user==null){
            result.setSuccess(false);
            result.setMessage("此登录用户不存在");
            result.setStatus("304");
        } else {
            result.setSuccess(true);
            result.setStatusCode(200);
            request.getSession().setAttribute("sysUserId",user.getId());
        }
        return result;
    }

    @RequestMapping("toAddInfo")
    public ModelAndView toAddInfo(String orderNo,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("addInfo");
        modelAndView.addObject("orderNo",orderNo);
        modelAndView.addObject("sysUserId",request.getSession().getAttribute("sysUserId"));
        return modelAndView;
    }

    @GetMapping("getTotal")
    @ResponseBody
    public PageResult getTotal(HttpServletRequest request){
        PageResult pageResult =null;
        try {
            pageResult= new PageResult();
            Map<String,Object> param = new HashMap<>();
            param.put("userId",request.getSession().getAttribute("userId"));
            Map m = orderService.getTotal(param);
            pageResult.setList(Arrays.asList(m));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;
    }


    /**
     * 根据日期查询订单
     * @return
     */
    @RequestMapping(value = "getListByDay",method = RequestMethod.GET)
    @ResponseBody
    public PageResult getListByDay(HttpServletRequest request,String day){
        PageResult pageResult = null;
        try {
            if(StringUtils.isEmpty(day)){
                pageResult = new PageResult();
            } else {
                Map<String,Object> map = new HashMap<>();
                map.put("day",day);
                map.put("status",1);
                map.put("userId",request.getSession().getAttribute("userId"));
                PageHelper.startPage(1,5);
                List<UserOrders> list = orderService.getList(map);
                pageResult = new PageResult(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;
    }

    /**
     * 根据id获取订单信息
     * @param id
     * @return
     */
    @RequestMapping("/getOrder")
    @ResponseBody
    public Result getOrder(Integer id,String orderNo){
        Result result = null;
        try {
            if(id!=null){
                UserOrders order = orderService.getOrder(id);
                result = new Result();
                result.setData(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 根据id获取订单信息
     * @param orderNo
     * @return
     */
    @RequestMapping("/getOrderByOrderNo")
    @ResponseBody
    public Result getOrderByOrderNo(String orderNo){
        Result result = null;
        try {
            if(StringUtils.isNotEmpty(orderNo)){
                UserOrders order = orderService.getOrderByOrderNo(orderNo);
                result = new Result();
                // 查询收件地人
                Map<String,Object> paramMap = new HashMap<>();
                paramMap.put("type",1);
                paramMap.put("id",order.getReceiveId());
                List<Address> list = addressService.query(paramMap);
                if(null != list && list.size()>0){
                    Address address = list.get(0);
                    order.setReceiveId(address.getName());
//                    recManInfo.setMobile(address.getPhone());
//                    recManInfo.setPrintAddr(address.getAddress());
                }
                result.setData(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 取消订单
     * @param orders
     * @return
     */
    @RequestMapping("cancelOrder")
    @ResponseBody
    public Result updateOrder(UserOrders orders){
        Result result = null;
        try {
            Integer id = orders.getId()!=null?orders.getId():null;
            if(id!=null){
                UserOrders order = orderService.getOrder(id);
                order.setStatus(9);
                order.setRemark(order.getRemark()+",由当前客户自己取消订单");
                int code = orderService.update(order);
                if(code!=0){
                    result = new Result();
                    result.setMessage("取消成功");
                    // 通知客服
                    Object ids = paramterUtil.getParametValue("sendmsg");
                    if(null !=ids){
                        String[] opids = ids.toString().split(",");
                        // 封装参数
                        Map<String,String> map = new HashMap<>();
                        map.put("first","您好，您的新的快件包裹已被取消。");
                        map.put("keyword1",order.getOrderNo());
                        Map<String,Object> param = new HashMap<>();
                        map.put("keyword2",order.getSendPhone());
                        map.put("keyword3", order.getSendCompany());
                        map.put("remark","请您跟进处理！");
                        for (String str: opids) {
                            WeixinUtil.sendDataToTemp(str, WechatConfig.WEIXIN_QX_MSGID,map);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询订单物流信息
     * @param orderId
     * @return
     */
    @RequestMapping("qeryOrderReceipt")
    @ResponseBody
    public com.express.common.result.Result qeryOrderReceipt(String orderId) {
        return com.express.common.result.Result.ok(orderService.qeryOrderReceipt(orderId));
    }
}
